package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.model.result.StarInfoResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.IPushExtHandleService;
import com.block.datapush.service.apipush.utils.YunWeiRongiUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/**
 * apib 撞库返回授权地址
 * 通知进件
 *
 */
@Service
public class WeiRongApiBPushApiService implements IPushApiService, IPushExtHandleService {

    private static final Logger log = LogFactory.getPushLog();

    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    private MerchantBaseInfoMapper merchantBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("phoneMd5", memberSourceInfo.getMobileMd5());
        paramMap.put("maskPhone", memberSourceInfo.getMobile().substring(0,8));
        paramMap.put("nameMd5", SecureUtil.md5(memberSourceInfo.getRealname()));
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("gender", 1);
        }else {
            paramMap.put("gender", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());

        paramMap.put("loanTime", YunWeiRongiUtil.getloantime(memberSourceInfo.getLoanTime()));
        paramMap.put("profession",YunWeiRongiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("zhima",YunWeiRongiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("providentFund",YunWeiRongiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("house",YunWeiRongiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("socialSecurity",YunWeiRongiUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("overdue",YunWeiRongiUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("commericalInsurance",YunWeiRongiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("vehicle",YunWeiRongiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("loanAmount",YunWeiRongiUtil.getloanmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("appKey",pushApiKeyParam.getApiKey());

        //加密
        String encrypt = YunWeiRongiUtil.encrypt(JSON.toJSONString(paramMap),pushApiKeyParam.getApiSecret());

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("channelId",pushApiKeyParam.getApiCode());
        bizMap.put("data",encrypt);

        String  checkUrl = pushApiKeyParam.getCheckUrl();

        log.info("【云薇融半流程】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), checkUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【云薇融半流程】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer respCode = resultObject.getInteger("code");
        String respMsg = resultObject.getString("msg");

        pushApiResult.setCode(respCode+"");
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(respCode.toString(), "0")) {
            JSONObject respData = resultObject.getJSONObject("data");
            String orderId = respData.getString("orderId");
            pushApiResult.setPushSuccess(true);
            pushApiResult.setOutOrderNo(orderId);
            extJson.put("outOrderNo",orderId);
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            pushApiResult.setSettleFlag(true);
            pushApiResult.setPushSuccess(true);
                //进行分润操作
                String priceType = pushApiKeyParam.getPriceType();
                BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                    BigDecimal price = respData.getBigDecimal("price");//下游返回分润前价格
                    if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceRight = price.divide(typeRate,2, RoundingMode.HALF_UP);
                    pushApiResult.setPrice(priceRight);
                    pushApiResult.setPriceRight(price);
                }

            return pushApiResult;
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String orderId = extJson.getString("outOrderNo");
        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("ip",memberSourceInfo.getReqIp());
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("gender", 1);
        }else {
            paramMap.put("gender", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanTime", YunWeiRongiUtil.getloantime(memberSourceInfo.getLoanTime()));
        paramMap.put("profession",YunWeiRongiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("zhima",YunWeiRongiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("providentFund",YunWeiRongiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("house",YunWeiRongiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("socialSecurity",YunWeiRongiUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("overdue",YunWeiRongiUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("commericalInsurance",YunWeiRongiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("vehicle",YunWeiRongiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("loanAmount",YunWeiRongiUtil.getloanmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("appKey",pushApiKeyParam.getApiKey());
        paramMap.put("orderId",orderId);
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String authUrl = StrUtil.format("{}/page/protocolWei/{}.html", appInfoByAppCode.getApiUrl(), memberSourceInfo.getUid());
        paramMap.put("agreeProtocol", authUrl);

        //加密
        String encrypt = YunWeiRongiUtil.encrypt(JSON.toJSONString(paramMap),pushApiKeyParam.getApiSecret());

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("channelId",pushApiKeyParam.getApiCode());
        bizMap.put("data",encrypt);

        String  registerUrl = pushApiKeyParam.getRegisterUrl();

        log.info("【云薇融半流程】 导单开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), registerUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(registerUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【云薇融半流程】导单结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer respCode = resultObject.getInteger("code");
        String respMsg = resultObject.getString("msg");
        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(respCode+"");
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(respCode.toString(), "0")) {
            String redirectUrl = data.getString("redirectUrl");
            pushApiResult.setApproveUrl(redirectUrl);
            pushApiResult.setOutOrderNo(orderId);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        // TODO: 2024/9/5 实现查询方法


        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        JSONObject jsonObject = JSON.parseObject(paramContent);
        String data = jsonObject.getString("data");
        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectById(Integer.valueOf(infoId));
        String data2 = YunWeiRongiUtil.decrypt(data,merchantBaseInfo.getApiKey());
        JSONObject jsonObject2 = JSON.parseObject(data2);
        if (ObjectUtil.isEmpty(jsonObject2)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }

        String orderId = jsonObject2.getString("orderId");
        noticeParamDTO.setOrderNo(orderId);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, orderId);

        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }

        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;


    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "0");
        jsonObject.put("msg", "回调成功");
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    @Override
    public StarInfoResult handleStarInfo(MerchantBaseInfo merchantBaseInfo, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        StarInfoResult starInfoResult = new StarInfoResult();
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);

        if (ObjectUtil.isEmpty(jsonObjectParamContent)) {
            return starInfoResult;
        }

        String mobileMd5 = jsonObjectParamContent.getString("mobileMd5");
        Integer startLevel = jsonObjectParamContent.getInteger("startLevel");
        starInfoResult.setMobileMd5(mobileMd5);
        starInfoResult.setStarLevel(startLevel);
        return starInfoResult;
    }
}
